//
//  CHDeviceViewController.swift
//  Checked
//
//  Created by admin on 09/03/2017.
//  Copyright © 2017 shinolr_go. All rights reserved.
//

import UIKit
import SwiftyJSON

var deviceCode: String?

class CHDeviceVController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
		view.backgroundColor = UIColor.white
		view.addSubview(webView)
		requestDeviceCode()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

	private lazy var webView: UIWebView = {
		let webView = UIWebView.init(frame: self.view.bounds)
		webView.delegate = self
		return webView
	}()

	private func requestDeviceCode() {
		NetworkManager.sharedManager.request(target: TraktApi.diveceCode) { (moyaResponse, _) in
			let data = moyaResponse?.data
			let json = JSON(data: data!)
			deviceCode = json["device_code"].string
			let verificationURL = json["verification_url"].url
			let userCode = json["user_code"]
			print(userCode)

			self.webView.loadRequest(URLRequest.init(url: verificationURL!))
//			self.requestAccessToken(code: deviceCode!)
		}
	}

	fileprivate func requestAccessToken(code: String) {
		NetworkManager.sharedManager.request(target: TraktApi.accessToken(code: code)) { (moyaResponse, _) in
			print(moyaResponse)
			print(moyaResponse?.response)
			let data = moyaResponse?.data
			let json = JSON(data: data!)
			print(data)
		}
	}
}

extension CHDeviceViewController: UIWebViewDelegate {
	func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
		print(request.url)
		return true
	}

	func webViewDidFinishLoad(_ webView: UIWebView) {
//		requestAccessToken(code: deviceCode!)

		let url = URL(string: "https://api.trakt.tv/oauth/device/token")!
		var request = URLRequest(url: url)
		request.httpMethod = "POST"
		request.addValue("application/json", forHTTPHeaderField: "Content-Type")

		request.httpBody = "{\n  \"code\": \(deviceCode),\n  \"client_id\": \(clientID),\n  \"client_secret\": \(clientSecret)\n}".data(using: .utf8)

		let task = URLSession.shared.dataTask(with: request) { data, response, error in
			if let response = response, let data = data {
				print(response)
				print(String(data: data, encoding: .utf8))
			} else {
				print(error)
			}
		}

		task.resume()
	}
}
